package com.onepower.core.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onepower.core.domain.response.MatchScheduleInfo;
import com.onepower.core.domain.response.MatchScoreInfo;
import com.onepower.core.exception.BizException;
import com.onepower.core.modules.repository.entity.MatchScheduleLocked;
import com.onepower.core.modules.repository.mapper.MatchScheduleLockedMapper;
import com.onepower.core.modules.service.IMatchScheduleLockedService;
import com.onepower.core.modules.service.IMatchScoreService;
import com.onepower.core.result.BizResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kin
 * @since 2018-08-12
 */
@Service
public class MatchScheduleLockedServiceImpl extends ServiceImpl<MatchScheduleLockedMapper, MatchScheduleLocked> implements IMatchScheduleLockedService {


    @Autowired
    private IMatchScoreService matchScoreService;

    @Override
    public void lockMatchSchedule(MatchScheduleLocked matchScheduleLocked) {
        int lockCount = baseMapper.selectCount(new QueryWrapper<MatchScheduleLocked>()
                .eq("match_id", matchScheduleLocked.getMatchId())
                .eq("match_admin_id", matchScheduleLocked.getMatchAdminId())
        );

        if (lockCount > 0) {
            throw new BizException(BizResultCode.MATCH_SCHEDULE_HAS_LOCKED);
        }
        baseMapper.insert(matchScheduleLocked);
    }

    @Override
    public void lockNextMatchSchedule(int matchId, int matchAdminId) {
        MatchScoreInfo scoreInfo = matchScoreService.getMatchScore(matchId, matchAdminId);
        if (scoreInfo == null) {
            throw new BizException(BizResultCode.MATCH_SCHEDULE_HAS_NO_SCORE);
        }

        baseMapper.update(null, new LambdaUpdateWrapper<MatchScheduleLocked>()
                .set(MatchScheduleLocked::getTwoTime, true)
                .eq(MatchScheduleLocked::getMatchId, matchId)
                .eq(MatchScheduleLocked::getMatchAdminId, matchAdminId)
                .eq(MatchScheduleLocked::getMatchScheduleId, scoreInfo.getMatchScheduleId())
        );
    }

}
